import { domain } from './domain.js';
import codeStatus from './codeStatus.js';
import { commonVersion } from '../common/apiString.js';
var mainName = domain;
var laravel_api = '/api/';
// #ifdef APP-PLUS
laravel_api = domain + '/api/';
// #endif
laravel_api = domain + '/api/';
function openoutherurl(url) {
  setTimeout(() => {
    window.open(url, '_blank');
  }, 100);
}
function downloadApp(requestFun) {
  const system_info = uni.getSystemInfoSync();
  let params = {
    os: system_info.platform //本机设备操作系统  （android || ios）
  };
  if (params.os != 'ios' && params.os != 'android') if (params.os != 'windows') return false; //如果不是安卓或ios 返回false

  //测试使用的是qqapk，上线清空
  var appUrl = '';
  //安卓
  var type = '';
  if (params.os != 'ios') {
    type = 'ANDROID';
  }
  //苹果
  if (params.os == 'ios') {
    type = 'IOS';
  }
  requestFun(
    {
      url: commonVersion,
      data: {
        type: type
      },
      type: 'post'
    },
    (res, msg) => {
      appUrl = res.address;
      var t = res.content;
      // #ifdef APP
      //移动端
      plus.runtime.openURL(appUrl);
      // #endif
      //#ifdef H5
      //alert(appUrl)
      //plus.runtime.openURL(appUrl)
      //window.location.href = appUrl;
      setTimeout(() => {
        window.open(appUrl, '_blank');
      }, 100);
      //#endif
    }
  );
}
function checkMobile(phone) {
  var reg = /^[1][0-9]{10}$/;
  return reg.test(phone);
}
function checkEmail(emial) {
  var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
  return reg.test(emial);
}
function showLayer(con, icon) {
  uni.showToast({
    icon: icon || 'none',
    title: con
    // duration:10000
  });
}

function initData(params, callback) {
  var invite_code = uni.getStorageSync('invite_code');
  var url = laravel_api + params.url;
  var mytype = params.type || 'GET';
  var data = params.data || {};
  // uni.showLoading({
  // 	title: '加载中',
  // 	mask: true
  // });
  uni.request({
    url,
    method: mytype,
    data,
    header: {
      'idc': invite_code,
      'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
    },
    success: res => {
      // uni.hideLoading();
      var resdata = res.data;
      // console.log(resdata);
      if (resdata.code == 200) {
        callback && callback(resdata.data, resdata.msg);
      } /*if(resdata.code==403){
			    uni.navigateTo({
			    	url:'/pages/login/login'
			    })
			}else*/ else {
        // uni.hideLoading();
        codeStatus(resdata.code, function (msg) {
          setTimeout(() => {
            showLayer(msg);
          }, 100);
        });
      }
    },
    fail: err => {
      console.log(err);
    },
    complete: () => {
      setTimeout(function () {
        uni.hideLoading();
      }, 2000);
    }
  });
}
function isEmpty(obj) {
  if (typeof obj == 'undefined' || obj == null || obj == '') {
    return true;
  } else {
    return false;
  }
}
function initDataToken(params, callback) {
  var token = uni.getStorageSync('token');
  // var lang=uni.getStorageSync('lang');
  var url = laravel_api + params.url;
  var mytype = params.type || 'GET';
  var data = params.data || {};
  if (mytype.toUpperCase() == 'POST') {
    //data=JSON.stringify(data)
    //console.log(data)
  }
  // uni.showLoading({
  // 	// title: '请求中...'
  // });
  uni.request({
    url,
    method: mytype,
    data,
    header: {
      'token': token,
      'Content-type': 'application/x-www-form-urlencoded'
    },

    success: res => {
      //uni.hideLoading();
      var resdata = res.data;
      if (resdata.code == 200) {
        callback && callback(resdata.data, resdata.msg);
      } else if (resdata == '{code=403, message=登录时间已过}') {
        uni.navigateTo({
          url: '/pages/login/login'
        });
      } else {
        // uni.hideLoading();
        codeStatus(resdata.code, function (msg) {
          setTimeout(() => {
            showLayer(msg);
          }, 100);
        });
      }
    },
    fail: () => {},
    complete: err => {
      //uni.hideLoading();
      if (err.statusCode == 500) {
        setTimeout(() => {
          showLayer(this.$t('bico.W631'));
        }, 100);
      }

      if (err.statusCode == 401) {
        uni.showModal({
          title: '',
          content: this.$t('bico.W630'),
          showCancel: true,
          cancelText: this.$t('bico.W628'),
          confirmText: this.$t('bico.W629'),
          success: res => {
            console.log(res);
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/mine/resetLegalPwd'
              });
            }
          },
          fail: () => {},
          complete: () => {}
        });
      }
    }
  });
}

function noshowToken(params, callback) {
  var token = uni.getStorageSync('token');
  var url = laravel_api + params.url;
  var mytype = params.type || 'GET';
  var data = params.data || {};
  uni.request({
    url,
    method: mytype,
    data,
    header: {
      'token': token,
      'Content-type': 'application/x-www-form-urlencoded'
    },

    success: res => {
      var resdata = res.data;
      if (resdata.type == 999) {
        uni.navigateTo({
          url: '/pages/mine/login'
        });
      } else if (resdata.type == '998') {
        uni.navigateTo({
          url: '/pages/mine/real_authentication'
        });
      } else if (resdata.type == '997') {
        uni.navigateTo({
          url: '/pages/mine/collect_money'
        });
      } else if (resdata.type == 'ok') {
        callback && callback(resdata.message, resdata.message);
      } else {
        setTimeout(() => {
          showLayer(resdata.message);
        }, 100);
      }
    },
    fail: () => {},
    complete: err => {
      if (err.statusCode == 500) {
        setTimeout(() => {
          showLayer(this.$t('bico.W631'));
        }, 100);
      }
    }
  });
}

function getGlobalSettting(params, callback) {
  // var url=laravel_api+params.url;
  var url = domain + '/' + params.url;
  var mytype = params.type || 'GET';
  var data = params.data || {};

  uni.request({
    url,
    method: mytype,
    data,
    header: {
      'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
    },
    success: res => {
      // uni.hideLoading();
      var resdata = res.data;
      console.log(res);
      callback && callback(resdata);
    },
    fail: err => {
      console.log(err);
    },
    complete: () => {
      setTimeout(function () {
        uni.hideLoading();
      }, 2000);
    }
  });
}
function getAddressOnline(params, callback) {
  var token = uni.getStorageSync('token');
  // var lang=uni.getStorageSync('lang');
  var url = domain + '/' + params.url;
  var mytype = params.type || 'GET';
  var data = params.data || {};
  console.log(url);
  console.log(data);
  uni.request({
    url,
    method: mytype,
    data,
    header: {
      'token': token,
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: res => {
      // uni.hideLoading();
      var resdata = res.data;
      // console.log(JSON.stringify(res));
      callback && callback(resdata);
    },
    fail: err => {
      console.log(err);
    },
    complete: () => {}
  });
}
const addNewAddr = data => {
  var addrList = JSON.parse(uni.getStorageSync('address_list'));
  addrList.push(data);
  uni.setStorageSync('address_list', JSON.stringify(addrList));
};
const getLocalAddrs = (filterName, flag = true) => {
  var addrList = JSON.parse(uni.getStorageSync('address_list'));
  return addrList.filter(item => {
    return item[filterName] == flag;
  });
};
const accMul = (arg1, arg2) => {
  var m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString();
  try {
    m += s1.split('.')[1].length;
  } catch (e) {}
  try {
    m += s2.split('.')[1].length;
  } catch (e) {}
  return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m);
};
const filterDecimals = (value, number = 2) => {
  let val = value - 0;
  let num = number - 0;
  let base = '1';
  let decimal = base.padEnd(num + 1, 0) - 0;
  let result = accMul(val, decimal);
  return (Math.floor(result) / decimal).toFixed(num);
};
function setTheme(type) {
  //设置导航栏
  if (type == 'dark') {
    uni.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#111d2f'
    });
  } else {
    uni.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#3e38ec'
    });
  }
}
function clearStorageSync() {
  uni.removeStorageSync('token');
  uni.removeStorageSync('tradeData');
  uni.removeStorageSync('fingerBool');
  uni.removeStorageSync('isface');
  uni.removeStorageSync('isFinger');
}
function setTitle(str) {
  uni.setNavigationBarTitle({
    title: str
  });
}
export default {
  setTitle,
  checkMobile,
  checkEmail,
  showLayer,
  clearStorageSync,
  initData,
  initDataToken,
  addNewAddr,
  getLocalAddrs,
  filterDecimals,
  mainName,
  noshowToken,
  getGlobalSettting,
  getAddressOnline,
  accMul,
  setTheme,
  isEmpty,
  downloadApp,
  openoutherurl
};
